package com.campus.counseling.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.campus.counseling.entity.CounselorAccount;
import com.campus.counseling.model.mapper.CounselorAccountMapper;
import com.campus.counseling.service.CounselorAccountService;
import com.campus.counseling.util.SecurityUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.time.LocalDateTime;
import java.time.LocalDate;
import java.util.Map;
import java.util.HashMap;

@Service
@RequiredArgsConstructor
public class CounselorAccountServiceImpl extends ServiceImpl<CounselorAccountMapper, CounselorAccount> implements CounselorAccountService {

    private final CounselorAccountMapper counselorAccountMapper;

    @Override
    public CounselorAccount getCurrentCounselorAccount() {
        return getOne(lambdaQuery()
                .eq(CounselorAccount::getCounselorId, SecurityUtils.getUserId())
                .last("LIMIT 1"));
    }

    @Override
    public Object getIncomeStats(String timeRange) {
        LocalDateTime startTime;
        LocalDateTime endTime = LocalDateTime.now();

        switch (timeRange) {
            case "day":
                startTime = LocalDate.now().atStartOfDay();
                break;
            case "week":
                startTime = LocalDate.now().minusWeeks(1).atStartOfDay();
                break;
            case "month":
                startTime = LocalDate.now().minusMonths(1).atStartOfDay();
                break;
            case "year":
                startTime = LocalDate.now().minusYears(1).atStartOfDay();
                break;
            default:
                startTime = LocalDate.now().minusDays(7).atStartOfDay();
        }

        return counselorAccountMapper.selectIncomeStats(SecurityUtils.getUserId(), startTime, endTime);
    }

    @Override
    public Object getAccountFlow(Integer pageNum, Integer pageSize, String flowType) {
        return counselorAccountMapper.selectSettlementHistory(
            new com.baomidou.mybatisplus.extension.plugins.pagination.Page<>(pageNum, pageSize),
            SecurityUtils.getUserId()
        );
    }

    @Override
    public Object getPendingSettlement() {
        Map<String, Object> result = new HashMap<>();
        result.put("amount", counselorAccountMapper.selectPendingSettlement(SecurityUtils.getUserId()));
        return result;
    }

    @Override
    public Object getSettlementHistory(Integer pageNum, Integer pageSize) {
        return counselorAccountMapper.selectSettlementHistory(
            new com.baomidou.mybatisplus.extension.plugins.pagination.Page<>(pageNum, pageSize),
            SecurityUtils.getUserId()
        );
    }
} 